package com.example.musicplayer.login

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.EditText
import android.widget.Toast
import android.widget.Button
import com.example.musicplayer.dao.UserProfileDAO
import com.example.musicplayer.model.UserProfile
import android.widget.ProgressBar
import com.example.musicplayer.R
import android.content.SharedPreferences
import com.example.musicplayer.MainActivity

class LoginActivity : AppCompatActivity() {
    private lateinit var usernameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var loginButton: Button
    private lateinit var registerButton: Button
    private lateinit var progressBar: ProgressBar
    private lateinit var userProfileDAO: UserProfileDAO
    private lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        usernameEditText = findViewById(R.id.username)
        passwordEditText = findViewById(R.id.password)
        loginButton = findViewById(R.id.login)
        registerButton = findViewById(R.id.register)
        progressBar = findViewById(R.id.loading)
        userProfileDAO = UserProfileDAO(this)
        sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE)

        loginButton.setOnClickListener {
            val username = usernameEditText.text.toString().trim()
            val password = passwordEditText.text.toString().trim()

            progressBar.visibility = ProgressBar.VISIBLE
            val userProfile = userProfileDAO.getUserProfileByUsernameAndPassword(username, password)
            progressBar.visibility = ProgressBar.GONE

            if (userProfile != null) {
                saveLoginState(true, userProfile.id)
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                Toast.makeText(this, "Login failed", Toast.LENGTH_SHORT).show()
            }
        }

        registerButton.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    private fun saveLoginState(isLoggedIn: Boolean, userId: Int) {
        val editor = sharedPreferences.edit()
        editor.putBoolean("isLoggedIn", isLoggedIn)
        editor.putInt("user_id", userId)
        editor.apply()
    }
}